import { defineStore } from 'pinia'
import { ref } from 'vue'
import AiCustomerServiceApi, { type ChatMessage, type ChatResponse } from '@/api/aiCustomerService'

export const useAiChatStore = defineStore('aiChat', () => {
    // 状态
    const messages = ref<ChatMessage[]>([])
    const isLoading = ref(false)
    const sessionId = ref<string>('')
    const suggestedReplies = ref<string[]>([])
    const isServiceOnline = ref(false)
    const healthCheckTimer = ref<number | null>(null)

    // 初始化聊天
    const initializeChat = async () => {
        // 添加欢迎消息
        const welcomeMessage: ChatMessage = {
            role: 'assistant',
            content: '您好！我是MES AI助手，很高兴为您服务！\n\n我可以帮助您：\n- 了解系统功能\n- 解答操作问题\n- 提供技术支持\n- 处理常见故障\n\n请告诉我您需要什么帮助？',
            timestamp: new Date().toISOString()
        }
        messages.value = [welcomeMessage]
    }

    // 发送消息
    const sendMessage = async (messageText: string): Promise<ChatResponse | null> => {
        if (!messageText.trim()) return null

        // 添加用户消息
        const userMessage: ChatMessage = {
            role: 'user',
            content: messageText,
            timestamp: new Date().toISOString()
        }
        messages.value.push(userMessage)

        // 设置加载状态
        isLoading.value = true

        try {
            // 调用API
            const response: ChatResponse = await AiCustomerServiceApi.sendMessage({
                message: messageText,
                sessionId: sessionId.value
            })

            // 添加AI回复
            const aiMessage: ChatMessage = {
                role: 'assistant',
                content: response.reply,
                timestamp: response.timestamp,
                usage: response.usage
            }
            messages.value.push(aiMessage)

            // 更新会话ID
            sessionId.value = response.sessionId

            return response

        } catch (error: any) {
            console.error('发送消息失败:', error)

            // 添加错误消息
            const errorMessage: ChatMessage = {
                role: 'assistant',
                content: '抱歉，我暂时无法回复您的消息。请检查网络连接或稍后重试。',
                timestamp: new Date().toISOString()
            }
            messages.value.push(errorMessage)

            throw error
        } finally {
            isLoading.value = false
        }
    }

    // 获取智能推荐回复
    const getSuggestedReplies = async (context: string): Promise<string[]> => {
        try {
            const suggestions = await AiCustomerServiceApi.getSuggestedReplies(context)
            suggestedReplies.value = suggestions
            return suggestions
        } catch (error) {
            console.error('获取推荐回复失败:', error)
            return []
        }
    }

    // 清理聊天记录
    const clearMessages = () => {
        messages.value = []
        sessionId.value = ''
        suggestedReplies.value = []
    }

    // 重置聊天状态
    const resetChat = () => {
        clearMessages()
        initializeChat()
    }

    // 获取聊天历史统计
    const getChatStats = () => {
        const userMessages = messages.value.filter(m => m.role === 'user').length
        const aiMessages = messages.value.filter(m => m.role === 'assistant').length
        const totalMessages = messages.value.length

        return {
            userMessages,
            aiMessages,
            totalMessages,
            hasHistory: totalMessages > 0
        }
    }

    // 导出聊天记录
    const exportChatHistory = () => {
        const chatData = {
            sessionId: sessionId.value,
            exportTime: new Date().toISOString(),
            messages: messages.value.map(msg => ({
                role: msg.role,
                content: msg.content,
                timestamp: msg.timestamp
            }))
        }

        const blob = new Blob([JSON.stringify(chatData, null, 2)], {
            type: 'application/json'
        })

        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `mes-ai-chat-${new Date().toISOString().split('T')[0]}.json`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(url)
    }

    // 检查服务健康状态
    const checkServiceHealth = async () => {
        try {
            const response = await AiCustomerServiceApi.checkHealth()
            isServiceOnline.value = response.status === 'healthy'
            return response
        } catch (error) {
            console.error('检查服务健康状态失败:', error)
            isServiceOnline.value = false
            return {
                status: 'error',
                message: '服务连接失败',
                timestamp: new Date().toISOString()
            }
        }
    }

    // 启动健康检查定时器
    const startHealthCheck = () => {
        // 立即检查一次
        checkServiceHealth()

        // 每30秒检查一次
        if (healthCheckTimer.value) {
            clearInterval(healthCheckTimer.value)
        }

        healthCheckTimer.value = setInterval(() => {
            checkServiceHealth()
        }, 30000)
    }

    // 停止健康检查定时器
    const stopHealthCheck = () => {
        if (healthCheckTimer.value) {
            clearInterval(healthCheckTimer.value)
            healthCheckTimer.value = null
        }
    }

    return {
        // 状态
        messages,
        isLoading,
        sessionId,
        suggestedReplies,
        isServiceOnline,

        // 方法
        initializeChat,
        sendMessage,
        getSuggestedReplies,
        clearMessages,
        resetChat,
        getChatStats,
        exportChatHistory,
        checkServiceHealth,
        startHealthCheck,
        stopHealthCheck
    }
}) 